<template>
  <div class="div-main">
    <div class="station-top">
      <el-form :inline="true" style="margin-top: 20px;" :model="form" :rules="rulesForm" ref="form">
        <el-form-item prop="date" label="日期" style=" margin-left: 50px;">
          <el-date-picker type="date" placeholder="选择日期" style="width: 180px;" v-model="form.date"></el-date-picker>
        </el-form-item>
        <el-form-item label="出发车站" style=" margin-left: 88px;" prop="start">
          <el-input placeholder="请输入车站" style="width: 180px;" v-model="form.start"></el-input>
        </el-form-item>

        <el-button icon="el-icon-refresh" circle style="margin-left: 70px; margin-right: 70px; background-color:#2dd4bf;"
          @click="exchangeStation"></el-button>

        <el-form-item label="到达车站" prop="end">
          <el-input placeholder="请输入车站" style="width: 180px;" v-model="form.end">
          </el-input>
        </el-form-item>

        <el-form-item style="margin-left: 50px;">
          <el-button :loading="queryLoading" type="primary" style="margin-left: 60px; " @click="setSearch('form')">{{
            queryLoading ? '查询中...' : '查询' }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="tableData" height=250 style="width:90%; margin-bottom: 10px;" strip
      :header-cell-style="{ background: '#f0f9ff', textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form class="expand">
            <div style="width:148px; text-align: center;">
              <span>历时：{{ props.row.time }}</span>
            </div>
            <div style="width:100px; text-align: center;">
              <span> ¥{{ props.row.businessPrice }}</span>
            </div>
            <div style="width:100px; text-align: center;">
              <span> ¥{{ props.row.firstPrice }}</span>
            </div>
            <div style="width:100px; margin-right: 146px; text-align: center;">
              <span> ¥{{ props.row.secondPrice }}</span>
            </div>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="index" width="80" label="序号">
      </el-table-column>
      <el-table-column prop="trainNumber" label="车次">
      </el-table-column>
      <el-table-column prop="startStation" label="出发站">
      </el-table-column>
      <el-table-column prop="startTime" label="出发时间">
      </el-table-column>
      <el-table-column prop="arriveStation" label="到达站">
      </el-table-column>
      <el-table-column prop="arriveTime" label="到达时间">
      </el-table-column>
      <el-table-column width="100" label="商务座">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.business > 3" effect="plain">{{ scope.row.business }}</el-tag>
          <el-tag type="danger" v-if="scope.row.business <= 3" >{{ scope.row.business }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column width="100" label="一等座">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.first = '有'" effect="plain">{{ scope.row.first }}</el-tag>
          <el-tag type="danger" v-if="scope.row.first != '有'" >{{ scope.row.first }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column width="100" label="二等座">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.second  = '有'" effect="plain">{{ scope.row.second }}</el-tag>
          <el-tag type="danger" v-if="scope.row.second != '有'" >{{ scope.row.second }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template slot-scope="scope">
          <el-button type="primary" size="small" style="width: 80px;" @click="addTicketForm(scope.row)">购买</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="div-footer">
      <span>总共有： {{ total }} 趟车</span>
    </div>

    <div>
      <el-drawer title="购票" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
        <div style="display: flex; flex-direction: column; justify-content: space-between;">
          <el-form :model="ticket" :rules="rulesTicket" ref="ticket" style="margin: 20px;">
            <el-form-item label="日期" label-width="80px">
              <el-date-picker type="date" style="width: 250px;" v-model="drawerForm.date"
                :disabled="true"></el-date-picker>
            </el-form-item>
            <el-form-item label="车次" label-width="80px">
              <el-input autocomplete="off" style="width: 250px;" :disabled="true"
                v-model="drawerForm.trainNumber"></el-input>
            </el-form-item>
            <el-form-item label="车站" label-width="80px">
              <el-input autocomplete="off" style="width: 100px;" :disabled="true"
                v-model="drawerForm.startStation"></el-input>
              <i class="el-icon-d-arrow-right" style="margin-left: 16px; margin-right: 16px;"></i>
              <el-input autocomplete="off" style="width: 100px;" :disabled="true"
                v-model="drawerForm.arriveStation"></el-input>
            </el-form-item>
            <el-form-item label="时间" label-width="80px">
              <el-input autocomplete="off" style="width: 100px;" :disabled="true" type="time"
                v-model="drawerForm.startTime"></el-input>
              <i class="el-icon-d-arrow-right" style="margin-left: 16px; margin-right: 16px;"></i>
              <el-input autocomplete="off" style="width: 100px;" :disabled="true" type="time"
                v-model="drawerForm.arriveTime"></el-input>
            </el-form-item>
            <el-form-item label="座位类型" label-width="80px" prop="seatType">
              <el-select placeholder="请选择活动区域" style="width: 250px;" v-model="ticket.seatType">
                <el-option label="商务座" value=0>
                  <el-tag>商务座</el-tag>
                </el-option>
                <el-option label="一等座" value=1>
                  <el-tag type="success">一等座</el-tag>
                </el-option>
                <el-option label="二等座" value=2>
                  <el-tag type="warning">二等座</el-tag>
                </el-option>
              </el-select>
              <span v-if="drawerForm.seatType == '0'" style="color: #818cf8; margin-left:10px;">{{
                drawerForm.businessPrice }}元/张</span>
              <span v-if="drawerForm.seatType == '1'" style="color: #818cf8; margin-left:10px;">{{ drawerForm.firstPrice
              }}元/张</span>
              <span v-if="drawerForm.seatType == '2'" style="color: #818cf8; margin-left:10px;">{{ drawerForm.secondPrice
              }}元/张</span>
            </el-form-item>
            <el-form-item label="乘车人" label-width="80px" prop="personId">
              <el-select multiple placeholder="请选择乘车人" style="width: 250px;" v-model="ticket.personId" collapse-tags>
                <el-option v-for="item in options" :key="item.id" :label="item.customerName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div style="width: 100%; padding: 15px; margin-top: 149px;">
            <el-button style="width: 200px;" @click="initTicket">取 消</el-button>
            <el-button type="primary" style="width: 200px;" @click="openDialog('ticket')">确定</el-button>
          </div>
        </div>
      </el-drawer>
    </div>

    <div>
      <el-dialog title="需支付的金额" :visible.sync="dialogVisible" width="30%">
        <div style="display: flex; flex-direction: column; justify-content: center;">
          <span v-if="ticket.seatType === '2'" style="margin-left: 20px; font-weight: bold;">票务类型为：二等座</span>
          <span v-if="ticket.seatType === '1'" style="margin-left: 20px; font-weight: bold;">票务类型为：一等座</span>
          <span v-if="ticket.seatType === '0'" style="margin-left: 20px; font-weight: bold;">票务类型为：商务座</span>
          <span style="margin-left: 20px; margin-top: 10px; font-weight: bold;">正常票数为：{{ ticketNumber.nomal }}(x{{
            ticketNumber.ticketPrice }}/张)</span>
          <span style="margin-left: 20px; margin-top: 10px; font-weight: bold;">优惠票数为：{{ ticketNumber.unnomal }}(x{{
            ticketNumber.discountPrice }}/张)</span>
          <span style="margin-left: 20px; margin-top: 10px; font-weight: bold;">总共票数为：{{ ticketNumber.total }}</span>
          <span style="margin-left: 20px; margin-top: 10px; font-size: xx-small;">注：学生、军人、儿童、残疾人均享受八折优惠</span>
          <el-divider></el-divider>
          <span
            style="margin-left: 20px; margin-top: 10px; font-weight: bold; font-weight: bold; font-size: large; color: red;">实付金额为：{{
              ticketNumber.price }}</span>
        </div>
        <span slot="footer">
          <el-button @click="cacelTicket()">取 消</el-button>
          <el-button type="primary" @click="setAddTicket()" :loading="loading">{{ loading ? '支付中 ...' : '确认支付'
          }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mul, add } from '../../../composables/data';
export default {
  name: "ticketFind",
  data() {
    return {
      // 查询按钮加载
      queryLoading: false,
      // 支付按钮加载
      loading: false,
      // 总车次数
      total: 0,
      // 车次数
      listData: [],
      // 查询车票表单
      form: {
        start: '武汉站',
        end: '长沙南站',
        date: '',
      },
      // 查询车票表单校验
      rulesForm: {
        date: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'blur' },
        ],
        start: [
          { required: true, message: '请输入始发站 ', trigger: 'blur' }
        ],
        end: [
          { required: true, message: '请输入目的站 ', trigger: 'blur' }
        ]
      },
      // 抽屉表单
      drawerForm: {
        trainId: '',
        trainNumber: '',
        startId: '',
        startStation: '',
        startTime: '',
        arriveId: '',
        arriveStation: '',
        arriveTime: '',
        businessPrice: 0,
        firstPrice: 0,
        secondPrice: 0,
        date: '',
      },
      // 车票表单
      ticket: {
        personId: [],
        seatType: '',
      },
      // 车票表单校验
      rulesTicket: {
        seatType: [
          { required: true, message: '请选择座位类型', trigger: 'blur' },
        ],
        personId: [
          { required: true, message: '请选择乘车人 ', trigger: 'blur' }
        ],
      },
      // 支付价格数据
      ticketNumber: {
        nomal: 0,
        unnomal: 0,
        total: 0,
        ticketPrice: 0.0,
        discountPrice: 0.0,
        price: 0.0
      },
      // 车票
      ticketForm: [],
      // 乘车人
      options: [],
      drawer: false,
      dialogVisible: false,
      direction: 'rtl',
    }
  },

  methods: {
    // 初始化车次
    init() {
      this.listData = [];
      this.total = 0;
    },
    // 交换车站
    exchangeStation() {
      var mid = this.form.start;
      this.form.start = this.form.end;
      this.form.end = mid;
    },
    // 初始化车票
    initTicket() {
      this.ticketForm = []
      this.ticketNumber.total = 0
      this.ticketNumber.nomal = 0
      this.ticketNumber.unnomal = 0
      this.ticketNumber.ticketPrice = 0.0
      this.ticketNumber.discountPrice = 0.0
      this.ticketNumber.price = 0.0
      this.ticket.seatType = ''
      this.ticket.personId = []
      this.drawer = false
    },

    // 查询车票校验
    setSearch(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.queryLoading = true
          this.init();
          const stationName = []
          stationName.push(this.form.start);
          stationName.push(this.form.end);
          setTimeout(() => {
            this.getAllTicket(stationName)
          }, 1000);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 查询车票
    getAllTicket(stationName) {
      this.request.get('/ticketVo/findTicket/' + stationName + "/" + this.form.date).then(
        response => {
          if (response.data.code === 1) {
            this.listData = response.data.data
            console.log(this.listData);
            this.total = this.listData.length
            this.$message({
              message: '查询成功',
              type: 'success',
              duration: 1000
            });
          } else {
            this.$message({
              message: '此时间段内无车次 ',
              type: 'info',
              duration: 1000
            })
          }
        },
        error => {
          console.log(error.message)
        }
      )
        .finally(() => {
          this.queryLoading = false
          // this.stationName = []
        })
    },
    // 初始化车票表单
    addTicketForm(ticket) {
      this.drawer = true;
      this.drawerForm.trainId = ticket.trainNumberId;
      this.drawerForm.trainNumber = ticket.trainNumber;
      this.drawerForm.startId = ticket.startId;
      this.drawerForm.startStation = ticket.startStation;
      this.drawerForm.startTime = ticket.startTime;
      this.drawerForm.arriveId = ticket.arriveId;
      this.drawerForm.arriveStation = ticket.arriveStation;
      this.drawerForm.arriveTime = ticket.arriveTime;
      this.drawerForm.businessPrice = ticket.businessPrice;
      this.drawerForm.firstPrice = ticket.firstPrice;
      this.drawerForm.secondPrice = ticket.secondPrice;
      this.drawerForm.date = new Date(this.form.date);
      // console.log(this.drawerForm);
    },
    // 初始化车票
    ticketBulk() {
      for (let item of this.ticket.personId) {
        let ticket = {
          trainId: 0,
          startId: 0,
          arriveId: 0,
          price: 0.0,
          seatType: 0,
          discountType: 0,
          personId: 0,
          status: 0,
          date: ''
        }
        ticket.personId = item;
        ticket.date =  this.drawerForm.date;
        ticket.trainId = this.drawerForm.trainId;
        ticket.startId = this.drawerForm.startId;
        ticket.arriveId = this.drawerForm.arriveId;
        ticket.seatType = Number(this.ticket.seatType);

        if (ticket.seatType === 2) {
          ticket.price = this.drawerForm.secondPrice;
        } else if (ticket.seatType === 1) {
          ticket.price = this.drawerForm.firstPrice;
        } else {
          ticket.price = this.drawerForm.businessPrice;
        }

        this.ticketNumber.ticketPrice = ticket.price
        this.ticketNumber.discountPrice = mul(ticket.price, 0.8).toFixed(1)
        for (let items of this.options) {
          if (items.id === item) {
            this.ticketNumber.total++;
            ticket.discountType = items.customerType
            if (items.customerType != 0) {
              this.ticketNumber.unnomal++
              ticket.price = this.ticketNumber.discountPrice
              this.ticketNumber.price = add(this.ticketNumber.price, ticket.price)
            } else {
              this.ticketNumber.nomal++
              this.ticketNumber.price = add(this.ticketNumber.price, ticket.price)
            }
          }
        }
        this.ticketForm.push(ticket);
      }
    },
    // 打开确认框
    openDialog(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.ticketBulk()
          this.dialogVisible = true;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 确认添加车票
    setAddTicket() {
      this.loading = true
      setTimeout(() =>
        this.addTicket(), 3000)
    },
    // 添加车票
    addTicket() {
      console.log(this.ticketForm);
      this.request.post('/ticket/addTicket', this.ticketForm).then(
        response => {
          if (response.data.code === 1) {
            this.dialogVisible = false
            this.$message({
              message: '购买成功',
              type: 'success',
              duration: 1000
            });
            const stationName = []
            stationName.push(this.form.start);
            stationName.push(this.form.end);
            this.getAllTicket(stationName)
            setTimeout(() => this.initTicket(), 100)
            
          } else {
            this.$message({
              message: response.data.msg,
              type: 'error',
              duration: 1000
            })
          }
        },
        error => {
          console.log(error.message)
        }
      ).finally(() => {
        this.loading = false
      }
      )
    },
    // 取消支付
    cacelTicket() {
      this.ticketForm = []
      this.ticketNumber.total = 0
      this.ticketNumber.nomal = 0
      this.ticketNumber.unnomal = 0
      this.ticketNumber.ticketPrice = 0.0
      this.ticketNumber.discountPrice = 0.0
      this.ticketNumber.price = 0.0
      this.ticket.seatType = ''
      this.ticket.personId = []
      this.dialogVisible = false
    },

    // 获取当前账户所有乘客
    getAllCustomer() {
      const findForm = {
        customerUser: this.userInfo.id
      }
      this.request.post('customer/getCustomer', findForm).then(
        response => {
          if (response.data.code === 1) {
            this.options = response.data.data
            console.log(this.options);
          }
        },
        error => {
          console.log(error.message)
        }
      )
    },
    // 确认是否关闭
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.initTicket()
          done();

        })
        .catch(_ => { });
    }
  },
  created() {
    this.userInfo = JSON.parse(sessionStorage.getItem('login_user'))
    this.getAllCustomer()
  },
  computed: {
    tableData() {
      let listMidData = this.listData
      for (let lm of listMidData) {
        if (lm.business > 8) {
          lm.business = '有'
        }
        if (lm.first > 20) {
          lm.first = '有'
        }
        if (lm.second > 20) {
          lm.second = '有'
        }
      }
      return listMidData
    }
  }
}

</script>

<style scoped>
.div-main {
  display: flex;
  height: 90%;
  width: 100%;
  flex-direction: column;
  align-items: center;
  flex-wrap: nowrap;
  align-content: center;
}

.station-top {
  border: 1px solid #6ee7b7;
  background-color: #f0fdfa;
  width: 90%;
  height: 90px;
  margin-bottom: 30px;
  margin-top: 10px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  align-content: center;
  flex-wrap: nowrap;
  flex-direction: row;
  /* text-align: center; */
}

.expand {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
  flex-wrap: nowrap;
  align-content: center;
  font-weight: bold;
  color: #334155;
}

.div-footer {
  /* margin-left: 100px; */
  font-size: larger;
  width: 780px;
  display: flex;
  justify-content: space-around;
}
</style>